package grib2handler.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;

public class FileUtil {
	public static final String GRIB2 = "grib2";
	public static final int BUFFER_MAX_SIZE = 1024;

	public static void main(String[] args) {
		write("E:\\123.txt", "hello", false);
	}

	/**
	 * 创建路径
	 * 
	 * @param path
	 */
	public static void creatPath(String path) {
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	/**
	 * 创建父路径
	 * 
	 * @param path
	 */
	public static void creatParentPath(String path) {
		File file = new File(path);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
	}

	/**
	 * 写数据到文件
	 * 
	 * @param path
	 *            路径
	 * @param content
	 *            内容
	 * @param append
	 */
	public static void write(String path, String content, boolean append) {
		BufferedWriter output = null;
		try {
			File f = new File(path);
			if (f.exists()) {
				System.out.println("文件存在");
			} else {
				System.out.println("文件不存在，正在创建...");
				if (f.createNewFile()) {
					System.out.println("文件创建成功！");
				} else {
					System.out.println("文件创建失败！");
				}
			}
			output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, append), "GBK"));
			output.write(new String(content.getBytes()));
			output.close();
			output = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null)
					output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取目录下的某类文件或目录
	 * 
	 * @param path
	 * @param suffix
	 * @return
	 */
	public static List<File> readPathFiles(String path, String suffix) {
		List<File> result = new ArrayList<File>();
		try {
			File file = new File(path);
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (suffix == null && !files[i].isDirectory()) {
					result.add(files[i]);
				} else if (!files[i].isDirectory() && files[i].getName().endsWith(suffix)) {
					result.add(files[i]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 读取某个文件
	 * 
	 * @param f
	 * @return
	 */
	public static String readFile(File f) {
		String s = new String();
		StringBuffer s1 = new StringBuffer();
		BufferedReader input = null;
		try {
			InputStreamReader isr = new InputStreamReader(new FileInputStream(f), "GBK");
			input = new BufferedReader(isr);
			while ((s = input.readLine()) != null) {
				s1.append(s).append("\n");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return s1.toString();
	}

	/**
	 * 删除目录
	 * 
	 * @param filepath
	 */
	public static void delPath(String filepath) {
		try {
			File f = new File(filepath);// 定义文件路径
			if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
				if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
					f.delete();
				} else {// 若有则把文件放进数组，并判断是否有下级目录
					File delFile[] = f.listFiles();
					int i = f.listFiles().length;
					for (int j = 0; j < i; j++) {
						if (delFile[j].isDirectory()) {
							delPath(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
						}
						delFile[j].delete();// 删除文件
					}
				}
			}
			f.delete();
		} catch (Exception e) {
		}
	}

	/**
	 * Untar TAR file
	 * 
	 * @param tarFile
	 * @param outPath
	 */
	public static boolean unTar(File tarFile, String outpath) {
		
		try {
			final InputStream is = new FileInputStream(tarFile);
			final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
			TarArchiveEntry entry = null;
			
			while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
				final File outputFile = new File(outpath.trim().equals("")?tarFile.getParent():outpath, entry.getName());
				if (entry.isDirectory()) {
					if (!outputFile.exists()) {
						if (!outputFile.mkdirs()) {
							throw new IllegalStateException(
									String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
						}
					}
				} else {
					final OutputStream outputFileStream = new FileOutputStream(outputFile);
					IOUtils.copy(debInputStream, outputFileStream);
					outputFileStream.close();
				}
			}
			debInputStream.close();
			is.close();
			return true;
			
		} catch (FileNotFoundException nfex) {
			nfex.printStackTrace();
			return false;
		} catch (IOException ioex) {
			ioex.printStackTrace();
			return false;
		} catch (ArchiveException ae) {
			ae.printStackTrace();
			return false;
		}
	}
}
